package com.bringspring.oauth.method.qywechat.granter;

import com.bringspring.oauth.method.detail.UserDetailsServiceImpl;
import com.bringspring.oauth.method.qywechat.token.WeComAuthenticationToken;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

public class WeComAbstractTokenGranter extends AbstractTokenGranter {

    private final UserDetailsServiceImpl userDetailsService;
    private static final String GRANT_TYPE = "WeCom";
    private final AuthenticationManager authenticationManager;
    public WeComAbstractTokenGranter(UserDetailsServiceImpl userDetailsService,AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
        this.userDetailsService=userDetailsService;

    }

    @SneakyThrows
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> requestParameters = tokenRequest.getRequestParameters();
        String code = requestParameters.get("code");
        String qyhCorpId = requestParameters.get("qyhCorpId");
        String qyhAgentId = requestParameters.get("qyhAgentId");
//        UserDetails u = userDetailsService.loadUserByWeComCode(code,qyhCorpId);
        UserDetails u = userDetailsService.loadUserByWeComCode(code, qyhCorpId, null);
        WeComAuthenticationToken weComAuthenticationToken = new WeComAuthenticationToken(code,u.getUsername(),u.getPassword());
        weComAuthenticationToken.setDetails(requestParameters);
        authenticationManager.authenticate(weComAuthenticationToken);
        OAuth2Request oAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(oAuth2Request,weComAuthenticationToken);
    }
}
